/*!
 * Table Page Template v0.0.1
 * Author: thon.ju
 * Email: thon.ju@gmail.com
 * Date: 2013-11-12 13:09
 * Description: display data by table page
 */

define(function(require, exports, module){
	
	var $ = require('jquery');
	require('jbox');
	require('spin/1.3/spin.js');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	template.openTag = '<$';
	template.closeTag = '$>';
	$.ajaxSetup({cache:false});
	
	module.exports = List;
	function List(){
		this.options = [];
	};
	
	
	
	/*==加载数据=======================================================================*/
	List.prototype.load = function load(callback) {
		
		var $this =this;
		var templateId = $this.options.template;
		var containerId = $this.options.container;

		var getting = $.get($this.options.links.list, $this.options.params);
		getting.done(function(data) {
			// 显示数据
			var html = template.render(templateId, data);
			$(containerId).empty().append(html);
			
			// page
			$(containerId + ' .pagination li a').click(function(){
				$this.page(this, callback);
			});
			
			// del
			$(containerId + ' .del-click').click(function(){		
				$this.del(this);
			});
			
			// update
			$(containerId + ' .update-click').click(function(){
				$this.update(this, callback);
			});
			
			if(typeof(callback) == "function"){
				callback(data);
			}
			
		});
	};

	List.prototype.page = function page(obj, callback) {
		var $this =this;
		var data = $.parseJSON($(obj).attr("data"));		
		$this.options.params.p=data.p;
		$this.options.params.s=data.s;
		$this.load(callback);
	};
	
	/* 删除数据 */
	List.prototype.del = function page(obj) {
		var $this =this;
		var id = $.parseJSON($(obj).attr("data"));		
		$.jBox.confirm("确定要删除这条记录吗？","提示",function(v,n,h){		
			if(v=='ok'){
			$.ajax({
			    url: $this.options.links.del+"/"+id,
			    type: 'DELETE',		    
			    success: function(result) {
			    	$(obj).parent().parent().parent().remove();
			    }
			});	
			}
			return true;
		});	
	};
	
	/*更新数据 */
	List.prototype.update = function update(obj, callback) {
		
		var $this =this;
	//	var templateId = $this.options.update.template;
	//	var containerId = $this.options.update.container;
		
		var data = $.parseJSON($(obj).attr("data"));
		    data = {"id":data};
		
	//	var html = template.render(templateId, data);
	//	$(containerId).empty().append(html);
		
		
		$('#update-modal').modal();
		
		$(".update-submit").click(function(){
			
			var postData = form2js('update-form', '.', true);
			postData["id"]=data.id;
			$.ajax({
				url : $this.options.links.update,
				type : "PUT",
				data :$.toJSON(postData),
				dataType : "json",
				contentType : "application/json",
				success : function() {					
					$this.load(callback);
					$.jBox.tip("修改成功");
					},
				error : function() {
					$.jBox.tip("修改失败");
				}
			});
		});
	};
	
	
});
